package com.jinglin.web.controller;

import com.jinglin.component.RedisComponent;
import com.jinglin.controller.ABaseController;
import com.jinglin.entity.constants.Constants;
import com.jinglin.entity.dto.TokenUserInfoDto;
import com.jinglin.entity.dto.UserCountInfoDto;
import com.jinglin.entity.vo.ResponseVO;
import com.jinglin.exception.BusinessException;

import com.jinglin.service.UserInfoService;
import com.jinglin.service.impl.UserFocusServiceImpl;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.util.HashMap;

@RestController
@RequestMapping("/account")
@Validated
public class AccountController extends ABaseController {
    @Autowired
    private RedisComponent redisComponent;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserFocusServiceImpl userFocusService;

    @PostMapping("/checkCode")
    public ResponseVO checkCode(){
        // 生成一个验证码图片
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(100, 42);
        String code = arithmeticCaptcha.text();
        String checkCodeBase64 = arithmeticCaptcha.toBase64();
        // 将验证码的值存入redis
        String key = redisComponent.saveCheckCode(code);
        HashMap<String,String> map = new HashMap<>();
        map.put("checkCode",checkCodeBase64);
        map.put("checkCodeKey",key);
        // 把验证码图片返回给前端
        return getSuccessResponseVO(map);
    }
    @RequestMapping("/register")
    public ResponseVO registry(@NotEmpty @Email  String email,
                               @NotEmpty String nickName,
                               @NotEmpty @Pattern(regexp = Constants.REGEX_PASSWORD) String registerPassword,
                               @NotEmpty String checkCode,
                               @NotEmpty String checkCodeKey){
        String  myCheckCode = redisComponent.getCheckCode(checkCodeKey);
        try {
            if (!myCheckCode.equalsIgnoreCase(checkCode)){
                throw new BusinessException("图形验证码不正确");
            }
            userInfoService.register(email,nickName,registerPassword);
            return getSuccessResponseVO(null);
        }finally {
            redisComponent.cleanCheckCode(checkCodeKey);
        }
    }
    @RequestMapping("/login")
    public ResponseVO login(HttpServletResponse response,
                            @NotEmpty  @Email String email,
                            // 注意这里穿过来的password已经在前端进行了md5加密
                            @NotEmpty  String password,
                            @NotEmpty  String checkCodeKey,
                            @NotEmpty  String checkCode){
        String  myCheckCode = redisComponent.getCheckCode(checkCodeKey);
        try {
            if (!myCheckCode.equalsIgnoreCase(checkCode)){
                throw new BusinessException("图形验证码不正确");
            }
            String ipAddr = getIpAddr();
            TokenUserInfoDto tokenDto = userInfoService.login(email, password, ipAddr);
            // 这个方法会将token塞到cookie里面，通过response返回给前端
            saveToken2Cookie(response,tokenDto.getToken());
            return getSuccessResponseVO(tokenDto);
        }finally {
            redisComponent.cleanCheckCode(checkCodeKey);
        }
    }
    @RequestMapping("/autoLogin")
    public ResponseVO autoLogin(HttpServletResponse response){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        if (tokenUserInfoDto == null){
            return getSuccessResponseVO(null);
        }
        // 如果过期时间小于一天,续期
        if (tokenUserInfoDto.getExpireAt() - System.currentTimeMillis() < Constants.REDIS_KEY_EXPIRES_DAY){
            // 重新拿一次token
            redisComponent.saveTokenInfo(tokenUserInfoDto);
            saveToken2Cookie(response,tokenUserInfoDto.getToken());
            return getSuccessResponseVO(tokenUserInfoDto);
        }
        return getSuccessResponseVO(tokenUserInfoDto);
    }
    @RequestMapping("/logout")
    public ResponseVO logout(HttpServletResponse response){
        cleanCookie(response,Constants.TOKEN_WEB);
        return getSuccessResponseVO("退出成功！！");
    }
    @PostMapping("/getUserCountInfo")
    public ResponseVO getUserCountInfo(){

        UserCountInfoDto userCountInfo = userInfoService.getUserCountInfo(getTokenUserInfoDto().getUserId());
        return getSuccessResponseVO(userCountInfo);
    }

}
